Two of the most common tasks performed with tabular data are sorting and paging.
In a large table, being able to rearrange the information that we're
looking for is invaluable. Unfortunately, these helpful operations can
be some of the trickiest to put into action.
First, we'll look at what it takes to perform table sorting, reordering data into a sequence that is most helpful to the user.
Server-side sorting
A common solution for data sorting is to perform it on the server side. Data in tables often comes from a database, which means that the code that pulls it out of the database can request it in a given sort order (using, for example, the SQL language's ORDER BY clause). If we have server-side code at our disposal, it is straightforward to begin with a reasonable default sort order.
Sorting is most useful, though, when the user can determine the sort order. A common method is to make the table headers (<th>) of sortable columns into links. These links can go to the current page, but with a query string appended indicating the column to sort by:
<table id="my-data">
<thead>
<tr>
<th class="name">
<a href="index.php?sort=name">Name</a>
</th>
<th class="date">
<a href="index.php?sort=date">Date</a>
</th>
</tr>
</thead>
<tbody>
...
</tbody>
</table>
The server can react to the query string parameter by returning the database contents in a different order.
Preventing page refreshes
This setup is simple, but
requires a page refresh for each sort operation. As we have seen, jQuery
allows us to eliminate such page refreshes by using AJAX methods. If we
have the column headers set up as links as before, we can add jQuery
code to change those links into AJAX requests:
$(document).ready(function() {
$('#my-data th a').click(function() {
$('#my-data tbody').load($(this).attr('href'));
return false;
});
});
Now when the anchors are
clicked, jQuery sends an AJAX request to the server for the same page.
When jQuery is used to make a page request using AJAX, it sets the X-Requested-With HTTP header to XMLHttpRequest
so that the server can determine that an AJAX request is being made.
The server code can be written to send back only the content of the<tbody>
element itself, and not the surrounding page, when this parameter is
present. This way we can take the response and insert it in place of the
existing<tbody> element.
This is an example of
progressive enhancement. The page works perfectly well without any
JavaScript at all, as the links for server-side sorting are still
present. When JavaScript is available, however, the AJAX hijacks the
page request and allows the sort to occur without a full page load.